package handel

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"rikao15/cache"
	"rikao15/model"
	"strconv"
	"time"
)

func Page(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var user []model.User
	reids_list := "redis_list" + strconv.Itoa(page)
	Datajson, _ := cache.Rdb.Get(cache.Ctx, reids_list).Result()
	if Datajson == "" {
		model.DB.Offset(offset).Limit(size).First(&user).Debug()
		JsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, reids_list, JsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(Datajson), &user)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "分页成功",
	})
	return

}
func Add(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "数据为空",
		})
		return
	}
	var user model.User
	err := model.DB.Create(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
		return
	}

}
